import 'package:flutter_blue_plus/flutter_blue_plus.dart';

/// 设备连接状态枚举
enum DeviceConnectionStatus {
  disconnected,  // 未连接
  connecting,     // 连接中
  connected,      // 已连接
  disconnecting,  // 断开连接中
  error,          // 连接错误
}

/// 设备信息模型
class DeviceInfo {
  final String id;
  final String name;
  final String? manufacturer;
  final String? model;
  final String? firmwareVersion;
  final int? rssi;
  final DateTime? lastSeen;
  final DeviceConnectionStatus connectionStatus;

  DeviceInfo({
    required this.id,
    required this.name,
    this.manufacturer,
    this.model,
    this.firmwareVersion,
    this.rssi,
    this.lastSeen,
    this.connectionStatus = DeviceConnectionStatus.disconnected,
  });

  /// 从BluetoothDevice创建设备信息
  factory DeviceInfo.fromBluetoothDevice(BluetoothDevice device, {int? rssi}) {
    return DeviceInfo(
      id: device.id.toString(),
      name: device.name.isNotEmpty ? device.name : 'Unknown Device',
      rssi: rssi,
      lastSeen: DateTime.now(),
      connectionStatus: DeviceConnectionStatus.disconnected,
    );
  }

  /// 转换为JSON格式
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
      'manufacturer': manufacturer,
      'model': model,
      'firmwareVersion': firmwareVersion,
      'rssi': rssi,
      'lastSeen': lastSeen?.toIso8601String(),
      'connectionStatus': connectionStatus.toString(),
    };
  }

  /// 从JSON格式创建设备信息
  factory DeviceInfo.fromJson(Map<String, dynamic> json) {
    return DeviceInfo(
      id: json['id'] ?? '',
      name: json['name'] ?? 'Unknown Device',
      manufacturer: json['manufacturer'],
      model: json['model'],
      firmwareVersion: json['firmwareVersion'],
      rssi: json['rssi'],
      lastSeen: json['lastSeen'] != null ? DateTime.parse(json['lastSeen']) : null,
      connectionStatus: _parseConnectionStatus(json['connectionStatus']),
    );
  }

  /// 解析连接状态字符串
  static DeviceConnectionStatus _parseConnectionStatus(String? status) {
    switch (status) {
      case 'DeviceConnectionStatus.connecting':
        return DeviceConnectionStatus.connecting;
      case 'DeviceConnectionStatus.connected':
        return DeviceConnectionStatus.connected;
      case 'DeviceConnectionStatus.disconnecting':
        return DeviceConnectionStatus.disconnecting;
      case 'DeviceConnectionStatus.error':
        return DeviceConnectionStatus.error;
      default:
        return DeviceConnectionStatus.disconnected;
    }
  }

  /// 复制设备信息并更新部分属性
  DeviceInfo copyWith({
    String? id,
    String? name,
    String? manufacturer,
    String? model,
    String? firmwareVersion,
    int? rssi,
    DateTime? lastSeen,
    DeviceConnectionStatus? connectionStatus,
  }) {
    return DeviceInfo(
      id: id ?? this.id,
      name: name ?? this.name,
      manufacturer: manufacturer ?? this.manufacturer,
      model: model ?? this.model,
      firmwareVersion: firmwareVersion ?? this.firmwareVersion,
      rssi: rssi ?? this.rssi,
      lastSeen: lastSeen ?? this.lastSeen,
      connectionStatus: connectionStatus ?? this.connectionStatus,
    );
  }

  @override
  String toString() {
    return 'DeviceInfo{id: $id, name: $name, rssi: $rssi, status: $connectionStatus}';
  }

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is DeviceInfo &&
          runtimeType == other.runtimeType &&
          id == other.id;

  @override
  int get hashCode => id.hashCode;
}

/// 设备服务特征模型
class DeviceServiceCharacteristic {
  final String serviceUuid;
  final String characteristicUuid;
  final String name;
  final String description;
  final bool canRead;
  final bool canWrite;
  final bool canNotify;

  DeviceServiceCharacteristic({
    required this.serviceUuid,
    required this.characteristicUuid,
    required this.name,
    required this.description,
    required this.canRead,
    required this.canWrite,
    required this.canNotify,
  });

  /// 从BluetoothCharacteristic创建设备服务特征
  factory DeviceServiceCharacteristic.fromBluetoothCharacteristic(
      BluetoothCharacteristic characteristic) {
    return DeviceServiceCharacteristic(
      serviceUuid: characteristic.serviceUuid.toString(),
      characteristicUuid: characteristic.uuid.toString(),
      name: _getCharacteristicName(characteristic.uuid.toString()),
      description: _getCharacteristicDescription(characteristic.uuid.toString()),
      canRead: characteristic.properties.read,
      canWrite: characteristic.properties.write,
      canNotify: characteristic.properties.notify,
    );
  }

  /// 获取特征名称
  static String _getCharacteristicName(String uuid) {
    // 根据标准UUID返回对应的特征名称
    switch (uuid.toLowerCase()) {
      case '00002a4f-0000-1000-8000-00805f9b34fb':
        return '通用数据特征';
      case '00002a50-0000-1000-8000-00805f9b34fb':
        return '命令数据特征';
      default:
        return '未知特征';
    }
  }

  /// 获取特征描述
  static String _getCharacteristicDescription(String uuid) {
    switch (uuid.toLowerCase()) {
      case '00002a4f-0000-1000-8000-00805f9b34fb':
        return '用于接收设备通知和读取数据';
      case '00002a50-0000-1000-8000-00805f9b34fb':
        return '用于发送命令和数据到设备';
      default:
        return '未知特征';
    }
  }

  @override
  String toString() {
    return 'DeviceServiceCharacteristic{name: $name, uuid: $characteristicUuid}';
  }
}

/// 设备通信状态模型
class DeviceCommunicationStatus {
  final bool isConnected;
  final bool isNotifying;
  final bool isSending;
  final String statusMessage;
  final int? negotiatedMtu;
  final DateTime? lastCommunicationTime;
  final int? packetsSent;
  final int? packetsReceived;
  final int? errors;

  DeviceCommunicationStatus({
    required this.isConnected,
    required this.isNotifying,
    required this.isSending,
    required this.statusMessage,
    this.negotiatedMtu,
    this.lastCommunicationTime,
    this.packetsSent,
    this.packetsReceived,
    this.errors,
  });

  /// 创建初始状态
  factory DeviceCommunicationStatus.initial() {
    return DeviceCommunicationStatus(
      isConnected: false,
      isNotifying: false,
      isSending: false,
      statusMessage: '等待连接...',
      packetsSent: 0,
      packetsReceived: 0,
      errors: 0,
    );
  }

  /// 复制通信状态并更新部分属性
  DeviceCommunicationStatus copyWith({
    bool? isConnected,
    bool? isNotifying,
    bool? isSending,
    String? statusMessage,
    int? negotiatedMtu,
    DateTime? lastCommunicationTime,
    int? packetsSent,
    int? packetsReceived,
    int? errors,
  }) {
    return DeviceCommunicationStatus(
      isConnected: isConnected ?? this.isConnected,
      isNotifying: isNotifying ?? this.isNotifying,
      isSending: isSending ?? this.isSending,
      statusMessage: statusMessage ?? this.statusMessage,
      negotiatedMtu: negotiatedMtu ?? this.negotiatedMtu,
      lastCommunicationTime: lastCommunicationTime ?? this.lastCommunicationTime,
      packetsSent: packetsSent ?? this.packetsSent,
      packetsReceived: packetsReceived ?? this.packetsReceived,
      errors: errors ?? this.errors,
    );
  }

  @override
  String toString() {
    return 'DeviceCommunicationStatus{connected: $isConnected, sending: $isSending, message: $statusMessage}';
  }
}